package whf.framework.security.web;

import java.util.List;

import whf.framework.entity.AbstractEntity;
import whf.framework.entity.Entity;
import whf.framework.i18n.ApplicationResource;
import whf.framework.security.UserContext;
import whf.framework.security.entity.Dept;
import whf.framework.security.entity.Group;
import whf.framework.security.entity.Role;
import whf.framework.security.entity.User;
import whf.framework.security.exception.UsernameAlreadyExistsException;
import whf.framework.security.service.DeptServiceImp;
import whf.framework.security.service.GroupService;
import whf.framework.security.service.GroupServiceImp;
import whf.framework.security.service.RoleService;
import whf.framework.security.service.RoleServiceImp;
import whf.framework.security.service.UserService;
import whf.framework.security.service.UserServiceImp;
import whf.framework.util.BeanInitialization;
import whf.framework.util.Utils;
import whf.framework.web.Constants;
import whf.framework.web.HttpHelper;
import whf.framework.web.struts.WebData;
import whf.framework.web.struts.WebDispatchAction;
import whf.framework.web.struts.WebForward;

/**
 * @author wanghaifeng
 * @email king@126.com
 * @modify 2006-05-31
 */
public class UserAction extends WebDispatchAction {

	@Override
	public WebForward prepareCreate(AbstractEntity webEntity, WebData data) throws Exception {
		long deptid = data.getLongParameter("deptId", 0);
		if(deptid > 0){
			Dept dept = DeptServiceImp.getDeptService().findByPrimaryKey(deptid);
			((User)webEntity).setDept(dept);
		}
		return super.prepareCreate(webEntity, data);
	}

	//加入到组
	public WebForward prepareAddToGroup(AbstractEntity webEntity, WebData data) throws Exception {
		List<Group> groups = GroupServiceImp.getGroupService().findAll();
		data.setAttribute("groups", groups);
		long id = webEntity.getId();
		User user = UserServiceImp.getUserService().findByPrimaryKey(id);
		user.setWebMethod("addToGroup");
		data.setAttribute(user);
		String selectedValues = "";
		for(Entity bo: groups){
			Group group = (Group)bo;
			if(group.contains(user)){
				if(selectedValues.equals("")){
					selectedValues=String.valueOf(group.getId());
				} else {
					selectedValues += ";"+String.valueOf(group.getId());
				}
			}
		}
		data.setAttribute("selectedValues", selectedValues);
		return data.forward("addToGroup");
	}
	
	public WebForward addToGroup(AbstractEntity webEntity, WebData data) throws Exception {
		long[] groupIds = data.getLongParameters("group", 0);
		List<Group> groups = Utils.newArrayList();
		GroupService groupService = GroupServiceImp.getGroupService();
		for(long groupId: groupIds){
			groups.add((Group)groupService.findByPrimaryKeyWithoutLazy(groupId));
		}
		UserService userService = UserServiceImp.getUserService();
		User user = userService.findByPrimaryKey(webEntity.getId());
		userService.assignUserGroups(user, groups);
		data.setAttribute(Constants.MESSAGE_THEN_CLOSE,"i18n.OK");
		return data.forward("addToGroup");
	}
	
	public WebForward prepareAddToRole(AbstractEntity webEntity, WebData data) throws Exception {
		User user = ((UserService)super.getService()).findByPrimaryKey(webEntity.getId());
		user.setWebMethod("addToRole");
		RoleService roleService = RoleServiceImp.getRoleService();
		List<Role> roles = Utils.newArrayList();
		roles.addAll(roleService.findByUser(user));
		StringBuilder sb = new StringBuilder();
		for(Role role: roles){
			if(sb.length() > 0) sb.append(";");
			sb.append(role.getId());
		}
		data.setAttribute(user);
		data.setAttribute("selectedValues", sb.toString());
		data.setAttribute("roles", roleService.findAll());
		return data.forward("addToRole");
	}
	
	public WebForward addToRole(AbstractEntity webEntity, WebData data) throws Exception {
		long[] roleIds = data.getLongParameters("role", 0);
		List<Role> roles = Utils.newArrayList();
		RoleService roleService = RoleServiceImp.getRoleService();
		if(roleIds != null)
			for(long roleId: roleIds){
				BeanInitialization.setInitializeProperties(new String[]{"users"});
				roles.add((Role)roleService.findByPrimaryKeyWithoutLazy(roleId));
			}
		UserService userService = UserServiceImp.getUserService();
		User user = userService.findByPrimaryKey(webEntity.getId());
		userService.assignUserRoles(user, roles);
		
		data.setAttribute(Constants.MESSAGE_THEN_CLOSE,"i18n.OK");
		return data.forward("addToRole");
	}
	
	/**
	 * 新用户注册
	 * @modify wanghaifeng Jan 8, 2007 10:52:56 AM
	 * @param mapping
	 * @param webEntity
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public WebForward register(AbstractEntity webEntity, WebData data) throws Exception {
		WebForward result = data.forward("register");
		webEntity.setWebMethod("submitRegistion");
		data.setAttribute(webEntity);
		return result;
	}

	/**
	 * 提交注册信息
	 * @modify wanghaifeng Jan 8, 2007 10:53:53 AM
	 * @param mapping
	 * @param webEntity
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public WebForward submitRegistion(AbstractEntity webEntity, WebData data) throws Exception {
		boolean registerResult = false;
		try{
			super.create(webEntity, data);
			registerResult = true;
		}catch(Exception e){
			Throwable cause = e.getCause();
			if(cause instanceof UsernameAlreadyExistsException){
				data.setAttribute("message", e.getMessage());
				return register(webEntity, data);
			} else {
				throw e;
			}
		}
		data.setAttribute("registerResult", registerResult);
		return data.forward("registerResult");
	}
	
	public WebForward activate(AbstractEntity webEntity, WebData data) throws Exception {
		UserService service = (UserService)super.getService();
		long[] userids = data.getLongParameters("id", 0);
		for(long userid: userids){
			User user = service.findByPrimaryKey(userid);
			if(!user.isAccountNonExpired() || !user.isAccountNonLocked() || 
					!user.isCredentialsNonExpired() || !user.isEnabled())
				service.activate(user);
			else 
				data.addPageMessage(ApplicationResource.get("auth.user.activate_already", user.getName()));
		}
		return list(webEntity, data);
	}
	
	public WebForward deactivate(AbstractEntity webEntity, WebData data) throws Exception {
		UserService service = (UserService)super.getService();
		long[] userids = data.getLongParameters("id", 0);
		for(long userid: userids){
			User user = service.findByPrimaryKey(userid);
			if(user.isAccountNonExpired() && user.isAccountNonLocked() && 
					user.isCredentialsNonExpired() && user.isEnabled())
				service.deactivate(user);
			else 
				data.addPageMessage(ApplicationResource.get("auth.user.deactivate_already", user.getName()));
		}
		return list(webEntity, data);
	}
	
	public WebForward profile(AbstractEntity webEntity, WebData data) throws Exception {
		UserContext userContext = data.getUserContext();
		data.setAttribute("UserContext", userContext);
		data.setAttribute(userContext.getUser());
		return data.forward("profile");
	}
} 